<template>
	<view class="delivery-container">
		<!-- 顶部标签页 -->
		<view class="tabs-wrapper">
			<order-status-tabs :tabs="tabs" v-model="currentTab" @change="handleTabChange" />
		</view>

		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-list" @scrolltolower="loadMore">
			<template v-if="orderList.length > 0">
				<order-card v-for="order in orderList" :key="order.id" :order="order">
					<template #actions>
						<button class="btn" v-if="order.status === 1" @tap="goToDelivery(order)">发货</button>
					</template>
				</order-card>
			</template>
			<template v-else>
				<view class="empty-wrapper">
					<uv-empty mode="order" text="暂无订单数据" :marginTop="0"></uv-empty>
				</view>
			</template>
		</scroll-view>
	</view>
</template>

<script>
import OrderStatusTabs from '@/components/OrderStatusTabs/OrderStatusTabs.vue'
import OrderCard from '@/components/OrderCard/OrderCard.vue'

export default {
	components: {
		OrderStatusTabs,
		OrderCard
	},
	data() {
		return {
			tabs: [
				{ name: '待发货', count: 0 },
				{ name: '已发货', count: 0 },
				{ name: '已签收', count: 0 }
			],
			currentTab: 0,
			orderList: [],
			trackingNo: '',
			currentOrder: null,
			page: 1,
			loading: false,
			hasMore: true,
			merchantId: null
		}
	},

	methods: {
		handleTabChange(index) {
			this.page = 1
			this.orderList = []
			this.hasMore = true
			this.loadOrders()
		},

		async loadOrders() {
			if (this.loading || !this.hasMore) return
			this.loading = true
			try {
				// 根据tab获取对应的订单状态
				const statusMap = {
					0: 1,  // 待发货
					1: 6,  // 已发货
					2: 2   // 已签收
				}
				const status = statusMap[this.currentTab]

				const res = await this.$http.post('/merchant/order/list', {
					status,
					pageNum: this.page,
					pageSize: 10,
					merchantId: this.merchantId
				})

				if (res) {
					const { items = [], total = 0 } = res || {}

					if (this.page === 1) {
						this.orderList = items
					} else {
						this.orderList = [...this.orderList, ...items]
					}

					this.hasMore = this.orderList.length < total
					if (items.length > 0) {
						this.page++
					}
				}
			} catch (e) {
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
			this.loading = false
		},

		async loadHeadCount() {
			try {
				const res = await this.$http.get(`/merchant/order/head?merchantId=${this.merchantId}`)
				if (res) {
					const counts = res || {}
					this.tabs = [
						{ name: '待发货', count: counts.waitShip || 0 },
						{ name: '已发货', count: counts.shipped || 0 },
						{ name: '已签收', count: counts.completed || 0 }
					]
				}
			} catch (e) {
				console.error('获取订单统计失败', e)
			}
		},

		loadMore() {
			if (!this.loading && this.hasMore) {
				this.loadOrders()
			}
		},

		// 跳转到发货页面
		goToDelivery(order) {
			uni.navigateTo({
				url: `/subpkg/goods_delivery_page/goods_delivery_page?orderId=${order.id}`
			})
		},

		closeShipDialog() {
			this.$refs.shipPopup.close()
			this.currentOrder = null
		},

		async confirmShip() {
			if (!this.trackingNo.trim()) {
				uni.showToast({
					title: '请输入物流单号',
					icon: 'none'
				})
				return
			}

			try {
				await this.$api.shipOrder({
					orderId: this.currentOrder.id,
					trackingNo: this.trackingNo
				})
				uni.showToast({
					title: '发货成功'
				})
				this.closeShipDialog()
				// 重新加载头部统计和订单列表
				await this.loadHeadCount()
				this.handleTabChange(this.currentTab)
			} catch (e) {
				uni.showToast({
					title: '发货失败',
					icon: 'none'
				})
			}
		}
	},

	onLoad(options) {
		this.merchantId = options.merchantId
		if (this.merchantId) {
			this.loadHeadCount()
			this.loadOrders()
		} else {
			uni.showToast({
				title: '缺少商家ID参数',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	}
}
</script>

<style lang="scss" scoped>
@import './goods_delivery.scss';
</style>
